package com.txw.oss.service.imp;

import com.aliyun.oss.OSSClient;
import com.txw.oss.utils.ConstantPropertiesUtil;
import com.txw.oss.service.OssService;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImp implements OssService {

    @Override
    public String uploadFileAvatar(MultipartFile file) {
        //工具类获取值
        //获取阿里云存储相关常量
        String endPoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
        try {
            //判断oss实例是否存在：如果不存在则创建，如果存在则获取
            OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);

            //获取上传文件流
            InputStream inputStream = file.getInputStream();

            //获取文件名称
            String fileName = file.getOriginalFilename();

            //在文件名称里面添加随机唯一的值
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            fileName = uuid + fileName;

            //获取当前时间
            String datePath = new DateTime().toString("yyyy/MM/dd");
            fileName = "HeadPortrait/" + datePath + fileName;
            //调用OSS方法实现上传
            ossClient.putObject(bucketName, fileName, inputStream);
            // 关闭OSSClient。
            ossClient.shutdown();
            //拼接上传之后文件返回的路径
            String url = "https://" + bucketName + "." + endPoint + "/" + fileName;
            System.out.println(url);
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;

        }

    }
}
